package com.liugh.util;


import cn.hutool.core.io.FileUtil;
import com.liugh.base.Constant;
import com.liugh.base.PublicResultConstant;
import com.liugh.fastDFS.FastDFSClient;
import com.liugh.fastDFS.FastDFSFile;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * 文件上传的工具类
 */
public class FileUpload {
    private final static Logger logger = LoggerFactory.getLogger(FileUpload.class);

    /**
     * 上传文件到fastDFS服务器
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static String saveFile(MultipartFile multipartFile) throws Exception {
        String[] fileAbsolutePath;
        String fileName = multipartFile.getOriginalFilename();
        String ext = FileUtil.extName(fileName); //获取文件的扩展名
        byte[] fileBuff;
        try (BufferedInputStream InputStream = new BufferedInputStream(multipartFile.getInputStream())) {
            int len1 = InputStream.available();
            fileBuff = new byte[len1];
            InputStream.read(fileBuff);
            FastDFSFile file = new FastDFSFile(fileName, fileBuff, ext);
            fileAbsolutePath = FastDFSClient.fileUpload(file);
            if (fileAbsolutePath == null) {
                throw new MyException(PublicResultConstant.UPLOAD_FILE_FAIL);
            }

            return Constant.FASTIP + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
        }
    }

//    /**
//     * 从fastDFS服务器上下载文件
//     */
//    private byte[] getFileFromFastDFS(String groupName,String filename) throws IOException, MyException {
//        StorageClient storageClient = getConnetction();
//        return storageClient.download_file(groupName, filename);
//    }

//    //将文件下载到服务器主机上
//    public static String downloadFileToLocal(String filePath,String group,String fileName) throws IOException, MyException {
//        FileUpload fileUpload = new FileUpload();
//        byte[] bytes = fileUpload.getFileFromFastDFS(group,fileName);
//        String localPath = filePath + group + fileName;
//        IOUtils.write(bytes,new FileOutputStream(localPath));
//        return localPath;
//    }

//    删除FasTDfs上的文件
    public static void delFastDFSFile(String group, String filename) {
        try {
            FastDFSClient.deleteFile(group, filename);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
